# -*- coding: utf-8 -*-
import ast
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10086': {
        #  kukapay PDD 3.8% 100-10000 dwc
        'API_KEY': '3F7MCHNT9Z0LA965MHLBFN0DAGHRU8G9WQEAQSGIVBKEJ5HFJU1STDQLWKYTBTRNVCBRIEF2KZLAILCPKXSNFMLXQPDDHPQDXFIVXOK7L660BYUHENZCJK7VROPBBMBK',
        'gateway': 'http://api.cokapay.com/api/pay/create_payorder?params=',
        'query_gateway': 'http://api.cokapay.com/api/pay/query_order?params=',
        'appId': '45b5a95b64a147fe9f82827969b4b9dc'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("key is: %s", s)
    return _gen_sign(s)


# 产品ID	产品名称
# 8000	网银支付
# 8002	银联快捷
# 8006	支付宝扫码
# 8007	支付宝H5
# 8037	微信扫码
# 8038	微信H5
# 8041	银联扫码
def _get_pay_type(service):
    if service == 'alipay_scan':
        return 8006
    elif service == 'alipay_h5':
        return 8007
    elif service == 'alipay_single':
        return 8015
    elif service == 'wechat':
        return 8037
    elif service == 'unionpay':
        return 8002
    return 8006


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("kukapay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchId', str(int(app_id))),
        ('appId', str(_get_app_id(app_id))),
        ('productId', str(_get_pay_type(service))),
        ('mchOrderNo', str(pay.id)),
        ('currency', 'cny'),
        ('amount', str(int(pay_amount * 100))),
        ('notifyUrl', '{}/pay/api/{}/kukapay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('subject', 'charge'),
        ('body', 'charge'),
        ('clientIp', str(_get_device_ip(info))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("kukapay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['mchOrderNo'])
    url = _get_gateway(app_id) + json.dumps(parameter_dict)
    response = requests.post(url, timeout=3, verify=False)
    res_obj = json.loads(response.text)
    _LOGGER.info("kukapay create charge response.text: %s", response.text)
    payParams = ast.literal_eval(response.text.encode("utf-8"))['payParams']
    res_obj['payParams'] = str(payParams).replace(" ", "").replace("'", "\"")
    verify_sign(res_obj, api_key)
    return {'charge_info': ast.literal_eval(res_obj['payParams'])['payUrl']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("kukapay notify data: %s, order_id is: %s", data, data['mchOrderNo'])
    verify_sign(data, api_key)
    pay_id = data['mchOrderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('kukapay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['payOrderId']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,0-订单生成,1-支付中,2-支付成功,3-业务处理完成
    if trade_status in ['2', '3']:
        _LOGGER.info('kukapay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = str(pay_order.id)
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchId', str(int(app_id))),
        ('appId', str(_get_app_id(app_id))),
        ('payOrderId', str(pay_order.third_id)),
        ('mchOrderNo', pay_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("kukapay query data: %s, order_id: %s", json.dumps(parameter_dict), pay_id)
    url = _get_query_gateway(app_id) + json.dumps(parameter_dict)
    response = requests.post(url, timeout=3, verify=False)
    _LOGGER.info("kukapay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = str(data['payOrderId'])
        total_fee = float(data['amount']) / 100.0
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 支付状态,0-订单生成,1-支付中,2-支付成功,3-业务处理完成
        if trade_status in ['2', '3']:
            _LOGGER.info('kukapay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('kukapay data error, status_code: %s', response.status_code)
